package my.location;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import my.location.locationPolicy.DefinedAction;
import my.location.locationPolicy.DefinedLocation;
import my.location.locationPolicy.LocationPolicy;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.thoughtworks.xstream.XStream;

public class LocationActivity extends Activity implements OnClickListener{
    /** Called when the activity is first created. */
	private static final String FILE_NAME = "configure.xml";
	private TextView outputTxtView;
	public static List<LocationPolicy> MyList;
	private CheckBox chkServiceStarted;
	private Button btnServiceStarted;
	private static final String TAG = "LOCATION DEMO"; 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        chkServiceStarted = (CheckBox) findViewById(R.id.startservice);
        chkServiceStarted.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if(isChecked){
                	Log.i(TAG, "onClick: starting service");  
                    startService(new Intent(LocationActivity.this, LocationService.class));  
                      
                }
                else{
                	Log.i(TAG, "onClick: stopping service");  
                    stopService(new Intent(LocationActivity.this, LocationService.class)); 
                }
            }
        });
     
        btnServiceStarted = (Button)findViewById(R.id.startservicebtn);
        btnServiceStarted.setOnClickListener(this);
        //Log.i("Activity Created","Created");
        
    }
 
	public void onClick (View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {  
	    case R.id.startservicebtn: 
	    	//MakeupMyOwnListAndShowforTestingPurpose();
	    	MyList = readXML();
	    	MyList = updatePolicyList(MyList, MyList);
	    	updateXML(MyList);
	    	for (LocationPolicy lp: MyList) {
	    		System.out.println("PolicyId: " + lp.getPolicyId());
	    		for (DefinedAction act: lp.getActions()) {
	    			System.out.println("Update Frequency: " + act.getUpdateFrequency());
	    		}
	    	}
	      break;  
	    }  
	}
	
	
	private void MakeupMyOwnListAndShowforTestingPurpose() {
		// TODO Auto-generated method stub
		 //set up action:
    	DefinedAction myActionType1 = new DefinedAction();
    	myActionType1.setActionId(1);
	    DefinedAction myActionType2 = new DefinedAction();
	    myActionType2.setActionId(2);
	    DefinedAction myActionType3 = new DefinedAction();
	    myActionType3.setActionId(3);
      
	   //Policy 1:
      LocationPolicy myPolicy1 = new LocationPolicy();
      DefinedLocation myLocation1 = new DefinedLocation();
      myLocation1.setLocationName("school");
      myLocation1.setLatitude(59.833);
      myLocation1.setLongitude(17.6502);
      myLocation1.setRadius(50);
      	//bond the actions to the policy1 
      myPolicy1.setPolicyName("my policy name1");
      myPolicy1.setDefinedLocation(myLocation1);
      List<DefinedAction> actions = new ArrayList<DefinedAction>();
      actions.add(myActionType1); actions.add(myActionType2);
	  myPolicy1.setActions(actions);
	  
      //Policy 2:
      LocationPolicy myPolicy2 = new LocationPolicy();
      DefinedLocation myLocation2 = new DefinedLocation();
      myLocation2.setLocationName("home");
      myLocation2.setLatitude(59.831);
      myLocation2.setLongitude(17.65);
      myLocation2.setRadius(1000);
      	
      myPolicy2.setPolicyName("my policy name2");
      myPolicy2.setDefinedLocation(myLocation2);
      List<DefinedAction> actions2 = new ArrayList<DefinedAction>();
      actions2.add(myActionType3); 
	  myPolicy2.setActions(actions2);
     
	  List<LocationPolicy> list = new ArrayList<LocationPolicy>();
	  list.add(myPolicy1);list.add(myPolicy2);
	  
	  // The policies list is generated
	  MyList = list; // The list is generated
	  
	  // Transform to XML to show on the screen
	  XStream xstr = new XStream();
	  xstr.alias("location", DefinedLocation.class);
	  xstr.alias("action", DefinedAction.class);
	  xstr.alias("policy",LocationPolicy.class);
	  String xml = xstr.toXML(list);
	  outputTxtView = (TextView)findViewById(R.id.outputXML);
	  outputTxtView.setText(xml);
		
	}

	protected List<LocationPolicy> readXML() {
		Intent it = this.getIntent();
		String eol = System.getProperty("line.separator");
		BufferedReader input = null;
		List<LocationPolicy> policies = new ArrayList<LocationPolicy>();
		try {
			input = new BufferedReader(new InputStreamReader(openFileInput(FILE_NAME)));
			String line;
			StringBuffer buffer = new StringBuffer();
			while ((line = input.readLine()) != null) {
				buffer.append(line + eol);
			}
			String xmlString = buffer.toString();
			XStream xstr = new XStream();
			xstr.alias("location", DefinedLocation.class);
			xstr.alias("action", DefinedAction.class);
			xstr.alias("policy",LocationPolicy.class);
			policies = (List<LocationPolicy>)xstr.fromXML(xmlString);
		} catch (FileNotFoundException e) {
			updateXML(policies);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return policies;
	}
	
	private List<LocationPolicy> updatePolicyList(List<LocationPolicy> currentList, List<LocationPolicy> newList) {
		List<LocationPolicy> updatedList = new ArrayList<LocationPolicy>();
		for (LocationPolicy currentLocation: currentList) {
			boolean found = false;
			for (LocationPolicy newLocation: newList) {
				if (newLocation.getPolicyId() == currentLocation.getPolicyId()) {
					updatedList.add(newLocation);
					found = true;
					break;
				} 
			}
			if (!found) {
				updatedList.add(currentLocation);
			}
		}
		return updatedList;
	}
	
	private void updateXML(List<LocationPolicy> currentList) {
		XStream xstr = new XStream();
		xstr.alias("location", DefinedLocation.class);
		xstr.alias("action", DefinedAction.class);
		xstr.alias("policy",LocationPolicy.class);
		try {
			FileOutputStream fout = openFileOutput(FILE_NAME, MODE_WORLD_READABLE);
			OutputStreamWriter osw = new OutputStreamWriter(fout);
			xstr.toXML(currentList,osw);
			osw.flush();
			osw.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}